package pro.cherish.knowledgeobjectstorage.core;

import io.minio.MinioClient;
import io.minio.Result;
import io.minio.messages.Item;
import lombok.Data;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.file.Path;
import java.util.stream.Stream;

@Data
public class MonioStorage implements Storage {

  private String endpoint;
  private String accessKey;
  private String secretKey;
  private String bucketName;
  /** 默认桶 */
  public static final String DEFAULT_BUCKET = "storage";

  @Override
  public void store(MultipartFile file, String keyName) {

  }

  @Override
  public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
      MinioClient minioClient;
      try {
          minioClient = new MinioClient(endpoint, accessKey, secretKey);
          boolean isExist = minioClient.bucketExists(bucketName);
          if (!isExist) {
              minioClient.makeBucket(DEFAULT_BUCKET);
              bucketName = DEFAULT_BUCKET;
          }
          // 使用putObject上传一个文件到存储桶中。
          minioClient.putObject(bucketName,keyName,inputStream,contentLength,contentType);
      } catch (Exception ex) {
          ex.printStackTrace();
      }
  }

  @Override
  public Stream<Path> loadAll() {
    return null;
  }

  @Override
  public Path load(String keyName) {
      MinioClient minioClient;
      try {
          minioClient = new MinioClient(endpoint, accessKey, secretKey);
          Iterable<Result<Item>> results = minioClient.listObjects(bucketName,keyName);
          for (Result<Item> result : results) {
              Item item = result.get();
              System.out.println(item.lastModified() + "\t" + item.size() + "\t" + item.objectName());
          }
      } catch (Exception e) {
          e.printStackTrace();
      }

    return null;
  }

  @Override
  public Resource loadAsResource(String keyName) {
    return null;
  }

  @Override
  public void delete(String keyName) {}

  @Override
  public String generateUrl(String keyName) {
    return null;
  }
}
